#include "pch.h"

std::unique_ptr<GraphicsDevice> GraphicsDevice::sInstance (new GraphicsDevice());

// Constructor
GraphicsDevice::GraphicsDevice()
{
    gameScreen = NULL;
    font = NULL;
    textColor = {};
}

// Load Image Function
SDL_Surface* GraphicsDevice::load_image(std::string filename)
{
    // Temporary Storage
    SDL_Surface *loadedImage = NULL;

    // Optimized Image
    SDL_Surface *optimizedImage = NULL;

    // Load the Image
    loadedImage = IMG_Load(filename.c_str());
    std::cout << "Loading: " << filename << std::endl;

    // Check for Load Errors
    if (loadedImage != NULL)
    {
        // Create an Optimized Image
        optimizedImage = SDL_DisplayFormat(loadedImage);

        if (optimizedImage != NULL)
        {
            std::cout << "Load Successful: " << filename << std::endl;
        }

        // Free the Old Image
        SDL_FreeSurface(loadedImage);

        // For Transparency
        // if (optimizedImage != NULL)
        // {
            // Map the Color Key
            // Uint32 colorkey = SDL_MapRGB(optimizedImage -> format, 0xFF, 0xFF, 0xFF);

            // Set all pixels of color R 0, G 0, B 0 to be transparent
            //SDL_SetColorKey(optimizedImage, SDL_SRCCOLORKEY, colorkey);
        //}

        // Reset
        loadedImage = NULL;
    }
    else
    {
        std::cout << "ERROR: Failed to load image: " << filename << std::endl;
    }

    return optimizedImage;
}

void GraphicsDevice::apply_surface(int x, int y, int w, int h, SDL_Surface *source, SDL_Surface *destination)
{
    // Make a Temporary Rectangle to Hold the Offsets
    SDL_Rect offset;

    // Give the offsets to the Rectangle
    offset.x = x;
    offset.y = y;
    offset.w = w;
    offset.h = h;

    // Blit the Surface
    SDL_BlitSurface(source, NULL, destination, &offset);
}

bool GraphicsDevice::init()
{
    // Initialize all SDL subsystems
    if (SDL_Init(SDL_INIT_EVERYTHING) == -1)
    {
        return false;
    }

    // Set up the Screen
    SDL_Surface* screen = SDL_SetVideoMode(SCREEN_WIDTH, SCREEN_HEIGHT, SCREEN_BPP, SDL_HWSURFACE);
    GraphicsDevice::sInstance->setGameScreen(screen);

    // Screen Check Error
    if (GraphicsDevice::sInstance->getGameScreen() == NULL)
    {
        return false;
    }

    // Initialize SDL_ttf
    if (TTF_Init() == -1)
    {
        return false;
    }

    // Set font
    GraphicsDevice::sInstance->setFont("fonts/JosefinSansEDIT-Bold.ttf", 20);
    GraphicsDevice::sInstance->setColor(255, 255, 255);

    // Caption
    SDL_WM_SetCaption("Home Run Contest vALPHA", NULL);

    // Initialize confirmation
    return true;
}
